// 临时调试工具：手动设置 OpenID
const storage = require('../../utils/storage.js');

Page({
  data: {
    currentOpenId: '',
    testOpenId: ''
  },

  onLoad() {
    this.loadCurrentOpenId();
  },

  // 加载当前 OpenID
  loadCurrentOpenId() {
    const userInfo = storage.getUserInfo();
    const openid = userInfo?.extraData?.openid || userInfo?.openid || '';
    
    this.setData({
      currentOpenId: openid || '未设置',
      testOpenId: openid
    });
  },

  // 输入测试 OpenID
  onOpenIdInput(e) {
    this.setData({
      testOpenId: e.detail.value
    });
  },

  // 设置测试 OpenID
  setTestOpenId() {
    const { testOpenId } = this.data;
    
    if (!testOpenId || !testOpenId.trim()) {
      wx.showToast({
        title: '请输入 OpenID',
        icon: 'none'
      });
      return;
    }

    const userInfo = storage.getUserInfo();
    
    if (!userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    // 添加 OpenID 到 extraData
    if (!userInfo.extraData) {
      userInfo.extraData = {};
    }
    userInfo.extraData.openid = testOpenId.trim();

    // 保存用户信息
    const saved = storage.saveUserInfo(userInfo);

    if (saved) {
      wx.showToast({
        title: '设置成功',
        icon: 'success'
      });
      
      this.loadCurrentOpenId();
    } else {
      wx.showToast({
        title: '设置失败',
        icon: 'none'
      });
    }
  },

  // 获取真实 OpenID（通过微信登录，复用微信支付接口）
  getRealOpenId() {
    wx.showLoading({
      title: '获取中...',
      mask: true
    });

    wx.login({
      success: (loginRes) => {
        if (loginRes.code) {
          console.log('✅ 获取到微信登录 code:', loginRes.code);
          
          // 🔥 调用后端接口（复用微信支付的 openid 接口）
          wx.request({
            url: 'https://api.playtruly.cn/api/wx/miniapp/login',
            method: 'POST',
            data: {
              code: loginRes.code
            },
            success: (res) => {
              wx.hideLoading();
              console.log('✅ 获取 openid 响应:', res.data);
              
              // 🔥 后端返回格式：{ code: 200, data: { openid, session_key }, msg: "success" }
              if (res.data.code === 200 && res.data.data && res.data.data.openid) {
                const openid = res.data.data.openid;
                
                // 自动填充到输入框
                this.setData({
                  testOpenId: openid
                });
                
                wx.showModal({
                  title: '获取成功',
                  content: `OpenID: ${openid}\n\n是否立即保存？`,
                  confirmText: '保存',
                  success: (modalRes) => {
                    if (modalRes.confirm) {
                      this.setTestOpenId();
                    }
                  }
                });
              } else {
                wx.showModal({
                  title: '获取失败',
                  content: res.data.msg || '后端接口返回异常',
                  showCancel: false
                });
              }
            },
            fail: (err) => {
              wx.hideLoading();
              console.error('❌ 请求失败:', err);
              
              wx.showModal({
                title: '网络错误',
                content: '请检查后端接口是否正常',
                showCancel: false
              });
            }
          });
        } else {
          wx.hideLoading();
          wx.showToast({
            title: '微信登录失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('❌ wx.login 失败:', err);
        wx.showToast({
          title: '获取失败',
          icon: 'none'
        });
      }
    });
  },

  // 清除 OpenID
  clearOpenId() {
    wx.showModal({
      title: '确认清除',
      content: '确定要清除 OpenID 吗？',
      success: (res) => {
        if (res.confirm) {
          const userInfo = storage.getUserInfo();
          
          if (userInfo && userInfo.extraData) {
            delete userInfo.extraData.openid;
            storage.saveUserInfo(userInfo);
          }
          
          this.setData({
            currentOpenId: '未设置',
            testOpenId: ''
          });
          
          wx.showToast({
            title: '已清除',
            icon: 'success'
          });
        }
      }
    });
  },

  // 返回
  goBack() {
    wx.navigateBack();
  }
});

